/**
 * 
 */
package com.shequan.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ailk.dazzle.util.data.JSONUtils;
import com.shequan.common.bean.ResultDataStruct;
import com.shequan.common.bean.ViewTextConstans;
import com.shequan.common.bean.WebConstants;
import com.shequan.pbinfo.bean.pojo.WorkJob;
import com.shequan.pbinfo.service.WorkJobService;
import com.shequan.silayer.internal.service.ItfEmailSendService;
import com.shequan.user.bean.bo.LoginSession;
import com.shequan.user.bean.bo.UserInfoBO;
import com.shequan.user.bean.bo.UserSession;
import com.shequan.user.bean.pojo.UserInfo;
import com.shequan.user.bean.pojo.UserWorkJobRlt;
import com.shequan.user.service.UserInfoExtService;
import com.shequan.user.service.UserInfoService;
import com.shequan.user.service.UserWorkJobRltService;

/**
 * <P>
 * Copyright 2012.
 * </p>
 * <P>
 * All Rights Reserved.
 * </p>
 * 
 * @author YuJF
 * @version 1.0, 2012-2-27
 * @see com.shequan.user.controller.UserController
 * @since 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger log = Logger.getLogger(UserController.class);

	private UserInfoService userInfoService;
	private UserInfoExtService userInfoExtService;
	private ItfEmailSendService itfEmailSendService;
	private WorkJobService workJobService;
	private UserWorkJobRltService userWorkJobRltService;

	public void setUserInfoExtService(UserInfoExtService userInfoExtService) {
		this.userInfoExtService = userInfoExtService;
	}

	public void setUserWorkJobRltService(
			UserWorkJobRltService userWorkJobRltService) {
		this.userWorkJobRltService = userWorkJobRltService;
	}

	public void setWorkJobService(WorkJobService workJobService) {
		this.workJobService = workJobService;
	}

	public void setItfEmailSendService(ItfEmailSendService itfEmailSendService) {
		this.itfEmailSendService = itfEmailSendService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/login")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.debug("---in login---");
		ResultDataStruct<UserSession> rds = new ResultDataStruct<UserSession>();
		String userName;
		String password;
		String verifyCode;
		String sessionCode;
		UserSession userSession;
		LoginSession loginSession;
		try {
			HttpSession session = request.getSession();
			loginSession = (LoginSession) session
					.getAttribute(WebConstants.LOGIN_SESSION);
			userName = request.getParameter("userName");
			password = request.getParameter("password");
			verifyCode = request.getParameter("verifyCode");
			// userSession = (UserSession)
			// request.getSession().getAttribute(WebConstants.USER_SESSION);
			sessionCode = (String) session.getAttribute("verifyCode");
			sessionCode = "abc1";
			// 用户名或密码为空
			if (userName == null || "".equals(userName) || password == null
					|| "".equals(password)) {// 用户密码为空
				rds.setBusiSuccess(false);
				rds.setMessage(ViewTextConstans.USER_NAME_PWD_ISNULL_MSG);
			} else if (verifyCode == null || "".equals(verifyCode)
					|| sessionCode == null) {// 验证码为空
				rds.setBusiSuccess(false);
				rds.setMessage(ViewTextConstans.VERIFY_CODE_EMPTY);
			} else if (!verifyCode.equals(sessionCode)) {// 验证码不正确
				rds.setBusiSuccess(false);
				rds.setMessage(ViewTextConstans.VERIFY_CODE_ISWRONG);
			} else if (sessionCode.equals(verifyCode)) {
				// loginTimes = 1;
				UserInfo userInfo = userInfoService.queryUserByUserNameAndPWD(
						userName, password);
				if (userInfo != null) {
					session.setAttribute(WebConstants.USER_SESSION, userInfo);
					rds.setBusiSuccess(true);
					rds.setMessage(ViewTextConstans.USER_LOGIN_SUCCESS_MEG);
				} else {
					rds.setBusiSuccess(false);
					rds.setMessage(ViewTextConstans.USER_NAME_PWD_ISWRONG_MSG);
				}
			}
			rds.setSuccess(true);
		} catch (Exception e) {
			log.error("登录失败", e);
			rds.setSuccess(false);
			rds.setMessage(ViewTextConstans.UNKNOW_ERROR_MSG);
			throw e;
		}
		String jsonData = JSONUtils.bean2JsonString(rds);
		log.debug(jsonData);
		response.getWriter().print(jsonData);
	}

	/**
	 * 验证邮箱是否可用
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/isEmailReg")
	public void regist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.debug("---in regist---");
		ResultDataStruct<String> rds = null;
		String userName;
		try {
			userName = request.getParameter("email");
			rds = userInfoService.isEmailReg(userName);
			rds.setSuccess(true);
		} catch (Exception e) {
			if (rds == null) {
				rds = new ResultDataStruct<String>();
			}
			log.error(e);
			rds.setSuccess(false);
			rds.setMessage(ViewTextConstans.UNKNOW_ERROR_MSG);
		}
		String jsonData = JSONUtils.bean2JsonString(rds);
		response.getWriter().print(jsonData);
	}

	/**
	 * 注册第一步：注册用户基础信息
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/regBaseInfo")
	public void registUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		log.debug("---in regBaseInfo---");
		ResultDataStruct<String> rds = null;
		String userName;
		String userPwd;
		String userPwdConfirm;
		String realName;
		String birthday;
		String gender;
		String job;
		UserSession userSession = new UserSession();
		try {
			HttpSession session = request.getSession();
			
			userName = request.getParameter("email");
			log.debug("userName:" + userName);
			rds = userInfoService.isEmailReg(userName);
			if (rds.isBusiSuccess()) {
				userPwd = request.getParameter("userPwd");
				userPwdConfirm = request.getParameter("userPwdConfirm");
				rds = userInfoService.isCorrectPwd(userPwd, userPwdConfirm);
				if (rds.isBusiSuccess()) {
					realName = request.getParameter("realName");
					birthday = request.getParameter("birthday");
					gender = request.getParameter("gender");
					job = request.getParameter("job");
					UserInfoBO userInfo = new UserInfoBO();
					userInfo.setUserName(userName);
					userInfo.setRealName(realName);
					userInfo.setUserPwd(userPwd);
					userInfo.setBirthday(birthday);
					userInfo.setGender(gender);
					rds = userInfoService.registBaseInfo(userInfo);
					if (rds.isBusiSuccess()) {
						UserInfoBO userInfoBo = new UserInfoBO();
						userInfoBo.setUserId(rds.getData());
						ResultDataStruct<String> extRds = userInfoExtService
								.addUserInfoExt(userInfoBo);
						if (extRds.isBusiSuccess()) {
							UserWorkJobRlt rlt = new UserWorkJobRlt();
							rlt.setUserInfoExtId(Integer.parseInt(extRds
									.getData()));
							rlt.setWorkJobId(Integer.parseInt(job));
							ResultDataStruct<String> rltRds = userWorkJobRltService
									.addWorkJobRlt(rlt);
							if(rltRds.isBusiSuccess()){
								userSession.setUserId(Integer.parseInt(rds.getData()));
								userSession.setUserName(userInfo.getUserName());
								session.setAttribute(WebConstants.USER_SESSION, userSession);
								itfEmailSendService.addEmailSend(userName, userPwd);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			if (rds == null) {
				rds = new ResultDataStruct<String>();
			}
			log.error("", e);
			rds.setSuccess(false);
			rds.setMessage(ViewTextConstans.UNKNOW_ERROR_MSG);
		}
		String jsonData = JSONUtils.bean2JsonString(rds);
		response.getWriter().print(jsonData);
	}

	/**
	 * 根据key验证用户激活信息
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/activite")
	public ModelAndView activityUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		log.debug("---in activityUser---");
		ResultDataStruct<UserInfo> rds = null;
		UserSession userSesstion;
		try {
			String userName = request.getParameter("userName");
			String encryptValue = request
					.getParameter(WebConstants.ENCRYPT_VALUE);
			rds = userInfoService.activityUserByKey(userName, encryptValue);
			if (rds.isBusiSuccess()) {
				userSesstion = new UserSession();
				userSesstion.setUserName(userName);
				userSesstion.setUserId(rds.getData().getUserId());
				request.getSession().setAttribute(WebConstants.USER_SESSION,
						userSesstion);
				return new ModelAndView("/pages/user/registStep2.jsp");
			}
		} catch (Exception e) {
			if (rds == null) {
				rds = new ResultDataStruct<UserInfo>();
			}
			log.error(e);
			rds.setSuccess(false);
			rds.setMessage(ViewTextConstans.UNKNOW_ERROR_MSG);

		}

		// 应跳转到公共错误页面
		return new ModelAndView("/pages/user/registStep2.jsp");
	}

	/**
	 * 注册第三步：丰富用户基础信息
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/fillinfo")
	public void enRichUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultDataStruct<String> rds = null;
		HttpSession session = request.getSession();
		UserSession userSession = (UserSession) session
				.getAttribute(WebConstants.USER_SESSION);
		String location = request.getParameter("location");
		String school = request.getParameter("school");
		String profession = request.getParameter("profession");
		String joinYear = request.getParameter("joinYear");
		String tel = request.getParameter("tel");

		UserInfoBO userInfoBo = new UserInfoBO();
		userInfoBo.setUserName(userSession.getUserName());
		userInfoBo.setTel(tel);
		try {
			rds = userInfoService.modifyUserInfo(userInfoBo);
			if (rds.isBusiSuccess()) {
				userInfoBo.setUserId(rds.getData());
				userInfoBo.setLocation(location);
				userInfoBo.setSchool(school);
				userInfoBo.setProfession(profession);
				userInfoBo.setJoinYear(joinYear);
				// 此处需要改为modifyUserInfo
				// rds = userInfoExtService.addUserInfoExt(userInfoBo);
			}
		} catch (Exception e) {
			if (rds == null) {
				rds = new ResultDataStruct<String>();
			}
			log.error(e);
			rds.setMessage(ViewTextConstans.UNKNOW_ERROR_MSG);
		}
		String jsonData = JSONUtils.bean2JsonString(rds);
		response.getWriter().print(jsonData);
	}

	@RequestMapping(value = "/workJobInfo")
	public void getWorkJob(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultDataStruct<List<WorkJob>> rds = workJobService.queryAllWorkJob();
		String jsonData = JSONUtils.bean2JsonString(rds);
		response.getWriter().print(jsonData);
	}
}